package com.filter;

import java.io.IOException;
        import javax.servlet.Filter;
        import javax.servlet.FilterChain;
        import javax.servlet.FilterConfig;
        import javax.servlet.ServletException;
        import javax.servlet.ServletRequest;
        import javax.servlet.ServletResponse;
        import javax.servlet.annotation.WebFilter;
        import javax.servlet.http.Cookie;
        import javax.servlet.http.HttpServletRequest;
        import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author 军大
 * 这里的@WebFilter("/index.jsp")里面过滤的意思是，在你用自动登录的时候，他会跳到index.jsp里面，同时在没有登录的情况下不能访问index.jsp
 */

/*@WebFilter("/index.jsp")*/
public class LoginFilter implements Filter {

    private String[] noLoginDongXi;

    @Override
    public void init(FilterConfig Config) throws ServletException {
        //重xml里面获取需要放行的string，然后split一下
        String noLoginPaths = Config.getInitParameter("noLoginPaths");
        System.out.println("noLoginPaths =123 " + noLoginPaths);
        if(noLoginPaths != null){
             noLoginDongXi = noLoginPaths.split(",");
        }
    }
    @Override
    public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException {
        //获取浏览器的response和request
        HttpServletRequest request=(HttpServletRequest)arg0;
        HttpServletResponse response=(HttpServletResponse)arg1;
        //无需拦截的servlet和jsp,没有登录的情况下可以访问的资源，放行资源使用
        for (String passSomething : noLoginDongXi) {
            if(passSomething == null || "".equals(passSomething)) {
                    continue;
            }
            if (request.getRequestURI().indexOf(passSomething) != -1){
                arg2.doFilter(arg0,arg1);
                    return;
            }
        }
        //获取session，判断登录成功与否
        HttpSession session = request.getSession();
        String loginSucessSession = (String)session.getAttribute("loginSucessSession");
        if(loginSucessSession==null || "".equals(loginSucessSession)){
            response.sendRedirect(request.getContextPath()+"/login.jsp");
            return;
        }else {
            //已通过验证，用户访问继续
            arg2.doFilter(arg0, arg1);
        }
    }

    @Override
    public void destroy() {
    }


}